#!/bin/bash

. /etc/cvmfsdrc
if [ -f /etc/cvmfsdrc.local ]; then
  . /etc/cvmfsdrc.local
fi

for reqvar in SHADOW_DIR PUB_DIR LOG_FILE
do
   eval value=\$$reqvar
   if [ -z "$value" ]; then
      echo "Set a value for $reqvar in /etc/cvmfsdrc"
      exit 1
   fi
done

if [ ! -f /etc/init.d/cvmfsd ]
then
   echo "cvmfsd service is not installed"
   exit 1
fi

ctrlbin=`which cvmfsd_ctrl 2>/dev/null`
if [ $? -ne 0 ]
then
   echo "cvmfsd_ctrl is not installed"
   exit 1
fi

syncbin=`which cvmfs_sync.bin 2>/dev/null`
if [ $? -ne 0 ]
then
   echo "cvmfs_sync.bin is not installed"
   exit 1
fi

mkdir -p "$PUB_DIR/catalogs"
if [ $? -ne 0 ]
then
   echo "Failed to create $PUB_DIR/catalogs"
   exit 1
fi

mkdir -p "$PUB_DIR/data"
if [ $? -ne 0 ]
then
   echo "Failed to create $PUB_DIR/data"
   exit 1
fi

/etc/init.d/cvmfsd status >/dev/null
status=$?
if [ $status -eq 1 ]
then
   echo "CernVM-FS is stopped"
   exit 1
elif [ $status -eq 2 ]
then
   echo "Another synchronization process is already running"
   exit 1
fi

touch $SHADOW_DIR/.cvmfscatalog
trap "" SIGHUP SIGINT SIGTERM

if [ -f "$SHADOW_DIR/.cvmfsdirtab" ]; then
   echo "Auto-creating nested catalogs..."
   for d in `cat "$SHADOW_DIR/.cvmfsdirtab"`
   do
      for subdir in `find "${SHADOW_DIR}$d" -maxdepth 1 -mindepth 1 -type d`
      do
         if [ `basename $subdir | head -c 1` != "." ]; then
           if [ ! -f "$subdir/.cvmfscatalog" ]; then
             echo "Auto-creating nested catalog in $subdir"
             touch "$subdir/.cvmfscatalog" 
           fi
         fi  
      done
   done
fi

$ctrlbin pause
if [ $? -ne 0 ]
then
   echo "Failed to pause cvmfsd"
   exit 1
fi

timestamp=`date "+%Y%m%d%H%M%S"`
cp "$LOG_FILE" "${LOG_FILE}.$timestamp"
gzip "${LOG_FILE}.$timestamp"

if [ "x$IMMUTABLES" != "x" ]; then
   IMMUTABLES="-i $IMMUATBLES"
fi
if [ "x$COMPAT_CATALOG" == "xyes" ]; then
   COMPAT_CATALOG="-c"
fi
if [ "x$KEYFILE" != "x" ]; then
  KEYFILE="-k $KEYFILE"
fi
if [ "x$CVMFS_LAZYATTACH" == "xyes" ]; then
  CVMFS_LAZYATTACH="-z"
fi
if [ "x$CVMFS_BOOKKEEPING" != "x" ]; then
  if [ ! -f $CVMFS_BOOKKEEPING ]; then
    touch $CVMFS_BOOKKEEPING
  fi
  CVMFS_BOOKKEEPING="-b $CVMFS_BOOKKEEPING"
fi
if [ "x$CVMFS_SYNC_THREADS" != "x" ]; then
  CVMFS_SYNC_THREADS="-t $CVMFS_SYNC_THREADS"
fi
$syncbin -s "$SHADOW_DIR" -r "$PUB_DIR" -l "$LOG_FILE" "$IMMUTABLES" $COMPAT_CATALOG $KEYFILE $CVMFS_LAZYATTACH $CVMFS_BOOKKEEPING $CVMFS_SYNC_THREADS 2>&1 | tee "${LOG_FILE}.sync.$timestamp"
if [ $PIPESTATUS -eq 0 ]; then
  $ctrlbin flush
fi

$ctrlbin resume
if [ $? -ne 0 ]
then
   echo "Failed to resume cvmfsd"
   exit 1
fi
